package com.car.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

public class IPUtil {
	private List<String> ipList = new ArrayList<>();
	private Connection conn = ConnectionPool.getConnection("carvoice_core", "root", "zhouzhou100428", "192.168.1.168");

	public List<String> getIpList() {
		return ipList;
	}

	public void getIPFrom66IP() {
		Document doc = DocUtil.getDoc(
				"http://www.66ip.cn/nmtq.php?getnum=50&isp=0&anonymoustype=3&start=&ports=&export=&ipaddress=&area=0&proxytype=2&api=66ip");
		String[] iplist = doc.body().text().split(" ");
		int i = 0;
		System.out.println("获取代理IP中...");
		for (String s : iplist) {
			if (checkAgent(s)) {
				this.ipList.add(s);
				System.out.println(s);
				i++;
			}
		}
		System.out.println("代理IP共" + i + "个");
	}

	public void getIPFromYouDaiLi() {
		Document doc = DocUtil.getDoc("http://www.youdaili.net/Daili/http/4347_3.html");
		Elements eles = doc.select("div.cont_font p");
		for (Element e : eles) {
			for (TextNode t : e.textNodes()) {
				System.out.println(t.text().trim().split("@")[0]);
			}
		}
	}

	public List<String> getIP() {
		List<String> list = new ArrayList<>();
		Statement st = null;
		ResultSet rs = null;
		String sql = "SELECT ip FROM ip";
		try {
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				String ip = rs.getString("ip");
				list.add(ip);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 验证代理是否可用，两次尝试，超时10秒
	 * 
	 * @param ip
	 *            代理ip
	 * @param port
	 *            代理端口
	 * @return true 如果可用，false 如果不可用
	 */
	public static boolean checkAgent(String ipandport) {
		String[] iport = ipandport.split(":");
		String ip = iport[0];
		int port = Integer.valueOf(iport[1]);
		boolean back = true;
		int i = 0;
		while (i < 2) {
			try {
				Jsoup.connect("http://bbs.pcauto.com.cn/forum-14359.html").proxy(ip, port).timeout(1000).get();
				break;
			} catch (Exception e) {
				i++;
				back = false;
			}
		}
		return back;
	}

	public void delete() {
		Statement st = null;
		Statement st2 = null;
		ResultSet rs = null;
		String sql = "SELECT id,ip FROM ip";

		try {
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				String ips = rs.getString("ip");
				int id = rs.getInt("id");
				boolean res = checkAgent(ips);
				if (!res) {
					String sql2 = "DELETE FROM ip WHERE ip='" + ips + "'";
					st2 = conn.createStatement();
					st2.executeUpdate(sql2);
					System.out.println(id + "\t" + ips);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	// 获得代理IP集合
	public static List<String> checkSaveProxyIp() {
		List<String> ips = new ArrayList<>();
		Document doc = DocUtil.getDoc("http://bbs.pcauto.com.cn/forum-14359.html");
		Element iplist = doc.select("div.cont_font p").get(0);
		System.out.println(Util.getMatched(iplist.text(), "\\d{1,}\\.\\d{1,}\\.\\d{1,}\\.\\d{1,}:\\d{1,}").group());
		return ips;
	}

	public void readFileByLines(String fileName) {
		File file = new File(fileName);
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			while ((tempString = reader.readLine()) != null) {
				System.out.println(tempString.split("@")[0]);
				insertIP(tempString.split("@")[0]);

			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
	}

	public void insertIP(String ip) {
		PreparedStatement ps = null;
		String sql = "INSERT INTO ip(ip) VALUES(?)";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, ip);
			ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		IPUtil i = new IPUtil();
		// i.readFileByLines("E:/HeYanWorkSpace/carvoice/src/1.txt");
		i.delete();
		// i.checkSaveProxyIp();
		// System.out.println("http://baa.bitauto.com/".split("/").length);
	}
}
